/*
* 物体选中控件
* */
import * as THREE from "three";
import $ from 'jquery'
import {DataShow,GetData} from "../buildData/DataShow";
import {GR} from "../utils/goPage";


//以鼠标为点，向场景中发射射线
let raycaster = new THREE.Raycaster();
//鼠标坐标对象
let mouse = new THREE.Vector2();
//用来存储射线照射到的几何体对象
let selectObjects=[];
let scene,camera;
let outlinePass;
export const initObjectSelect=(_scene,_camera,_outlinePass)=>{
  scene=_scene;
  camera=_camera;
  outlinePass=_outlinePass;
  window.addEventListener('click',onMouseClick);
  window.addEventListener('dblclick',onMouseDbClick);

}
function onMouseClick(event) {
  var x, y;
  x = event.clientX;
  y = event.clientY;
  var mainCanvas=event.path[0]
  mouse.x = ((event.clientX - mainCanvas.getBoundingClientRect().left) / mainCanvas.offsetWidth) * 2 - 1;
  mouse.y = -((event.clientY - mainCanvas.getBoundingClientRect().top) / mainCanvas.offsetHeight) * 2 + 1;
  raycaster.setFromCamera(mouse,camera);
  var intersects=raycaster.intersectObjects([scene],true);

  if (intersects.length===0){
    $('#label').attr("style","display:none;")//隐藏标签
    selectObjects.pop();
    outlinePass.selectedObjects=selectObjects;
    return;
  }
  if (intersects[0].object.type==="StoreSign"||intersects[0].object.type==="Store"||intersects[0].object.type==="StoreGroup"||intersects[0].object.type==="StoreGoods"){
    $('#label').attr("style","display:block;")//显示标签
    $('#label').css({left: x,top: y-40})//设置标签位置
    let type = intersects[0].object.type;
    let no=intersects[0].object.uuid;
    //获取当前选中对象的信息
    let s = DataShow(type,no);
    selectObjects.pop();
    selectObjects.push(intersects[0].object);
    $("#label").html(s);// 显示模型信
    outlinePass.selectedObjects=selectObjects;
  }else {
    $('#label').attr("style","display:none;")//隐藏标签
    selectObjects.pop();
    outlinePass.selectedObjects=selectObjects;
    return;
  }

}
function onMouseDbClick(event) {
  var x, y;
  x = event.clientX;
  y = event.clientY;
  var mainCanvas=event.path[0]
  mouse.x = ((event.clientX - mainCanvas.getBoundingClientRect().left) / mainCanvas.offsetWidth) * 2 - 1;
  mouse.y = -((event.clientY - mainCanvas.getBoundingClientRect().top) / mainCanvas.offsetHeight) * 2 + 1;
  raycaster.setFromCamera(mouse,camera);
  var intersects=raycaster.intersectObjects([scene],true);
  if (intersects.length===0){
    return;
  }
  if (intersects[0].object.type==="StoreSign"||intersects[0].object.type==="Store"||intersects[0].object.type==="StoreGroup"||intersects[0].object.type==="StoreGoods"){
    let type = intersects[0].object.type;
    let no=intersects[0].object.uuid;
    //获取当前选中对象的信息
    let getData = GetData(type,no);
    let gr = new GR();
    gr.goPage(getData);
  }else {
    return;
  }

}
